#!/usr/bin/python3
# -*- coding:utf-8 -*-
# __author__ == taoyulong2018@gmail.com
# __time__ == 2023/6/30 8:43
# ===========================================
#       题目名称： 59. 螺旋矩阵 II
#       题目地址： https://leetcode.cn/problems/spiral-matrix-ii/
#       题目描述： https://note.youdao.com/s/LWYgPSzT
# ===========================================


class Solution:
    def generateMatrix(self, n):
        # 定义好返回的螺旋矩阵
        spiral_matrix = [[0 for j in range(n)] for i in range(n)]
        # 初始化的螺旋矩阵  定义一下下标 然后根据规则依次删除
        temp_spiral_matrix = [[(i, j) for j in range(n)] for i in range(n)]

        cur_val = 1
        while temp_spiral_matrix:
            # 从左往右删
            lr = temp_spiral_matrix[0]
            del temp_spiral_matrix[0]
            for (x, y) in lr:
                spiral_matrix[x][y] = cur_val
                cur_val += 1
            if not temp_spiral_matrix:
                break
            # 从右往下删
            cur_index = 0
            while cur_index < len(temp_spiral_matrix):
                x, y = temp_spiral_matrix[cur_index][-1]
                del temp_spiral_matrix[cur_index][-1]
                spiral_matrix[x][y] = cur_val
                cur_val += 1
                cur_index += 1
            if not temp_spiral_matrix:
                break
            # 从下往左删
            ul = temp_spiral_matrix[len(temp_spiral_matrix) - 1]
            del temp_spiral_matrix[len(temp_spiral_matrix) - 1]
            for index in range(len(ul) - 1, -1, -1):  # 倒叙
                x, y = ul[index]
                spiral_matrix[x][y] = cur_val
                cur_val += 1
            if not temp_spiral_matrix:
                break
            # 从左往上删
            cur_index = len(temp_spiral_matrix) - 1
            while cur_index >= 0:
                x, y = temp_spiral_matrix[cur_index][0]
                del temp_spiral_matrix[cur_index][0]
                spiral_matrix[x][y] = cur_val
                cur_val += 1
                cur_index -= 1

        return spiral_matrix


if __name__ == '__main__':
    s = Solution()
    # [[1,2,3],[8,9,4],[7,6,5]]
    print("n = 3 =>", s.generateMatrix(n=3))
    # [[1]]
    print("n = 1 =>", s.generateMatrix(n=1))
    #
    print("n = 4 =>", s.generateMatrix(n=4))
